package com.qnvip.sbd.mybatis.sqlprovider;

import com.qnvip.sbd.mybatis.util.ObjectStruct;
import com.qnvip.sbd.util.StringUtil;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Map;

/**
 * 
 * 
 * @author Ericlin
 *
 */
public class SqlConditionProvider {

	private StringBuilder condition = new StringBuilder();

	private Object object = null;

	public SqlConditionProvider(Object object) {
		this.object = object;
	}

	private void process(Object obj)
			throws IllegalAccessException, IllegalArgumentException, InvocationTargetException {
		if (obj == null) {
			return;
		}

		ObjectStruct objectStruct = new ObjectStruct(obj);
		Map<String, Method> getMethods = objectStruct.getGetMethods();
		Field[] fields = obj.getClass().getDeclaredFields();
		for (int i = 0; fields != null && i < fields.length; i++) {
			Method getMethod = getMethods.get(fields[i].getName());
			if (getMethod != null) {
				String filed = StringUtil.camelToUnderline(fields[i].getName());
				Object value = getMethod.invoke(obj);
				if (value != null) {
					condition.append("and ").append(filed).append("=#{condition.").append(fields[i].getName()).append("} ");
				}
			}
		}
	}

	public String getCondition() throws IllegalAccessException, IllegalArgumentException, InvocationTargetException {
		if (condition == null || condition.length() == 0) {
			process(object);
		}
		return condition.toString();
	}

}
